package example.demo.web;

import example.demo.enums.ErrorCode;
import example.demo.exception.ListValidException;
import example.demo.vo.ResultVO;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice(basePackages = "example.demo.controller")
@ResponseBody
public class CtrlAdvice {

    /*
     {
     "success": false,
     "code": "1000",
     "msg": "参数不正确",
     "data": {
         "localDateTime": "不能为null",
         "email": "不是一个合法的电子邮件地址"
     }
     */
    @ExceptionHandler
    public ResultVO exceptionHandler(MethodArgumentNotValidException e) {
        Map<String, String> collect = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResultVO.fail(ErrorCode.PARAM_ERROR, collect);
    }

    @ExceptionHandler
    public ResultVO exceptionHandler(ConstraintViolationException e) {
        Map<Path, String> collect = e.getConstraintViolations().stream()
                .collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage));
        return ResultVO.fail(ErrorCode.PARAM_ERROR, collect);
    }


    @ExceptionHandler
    public ResultVO exceptionHandler(ValidationException e) {
        Map<Integer, Map<Path, String>> map = new HashMap<>();
        ((ListValidException) e.getCause()).getErrors().forEach((integer, constraintViolations) -> {
            map.put(integer, constraintViolations.stream()
                    .collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage)));
        });
        return ResultVO.fail(ErrorCode.PARAM_ERROR, map);
    }

    @ExceptionHandler
    public ResultVO exceptionHandler(Exception e) {
        return ResultVO.fail(ErrorCode.SYSTEM_ERROR);
    }
}
